<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">
              状态：
              <a-tag color="#87d068">{{ data.form.docStatus }}</a-tag>
            </h3>
            <h3 style="display: inline">
              审核：
              <a-tag color="#87d068">{{ data.form.approved ? '已审核' : '未审核' }}</a-tag>
            </h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()">返回</a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)"
                >保存
              </a-button>
              <a-button @click="edit()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)"
                >编辑
              </a-button>
              <a-button @click="del()" v-if="data.form.docStatus === 'O' && !data.form.approved   && !data.form.edit">删除</a-button>

              <a-button @click="approved()" v-if="!data.form.edit">查看审核</a-button>
              <a-dropdown>
                <a-button v-if="!(data.form.edit || data.form.docStatus === 'L')">更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" v-if="(data.form.docStatus !== 'C')">关闭单据</a-menu-item>
                    <a-menu-item key="b" v-if="(data.form.docStatus === 'C')">打开单据</a-menu-item>
                    <a-menu-item key="c" v-if="!data.form.approved">发起审核</a-menu-item>
                    <a-menu-item key="d" v-if="data.form.approved">取消审核</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="月期间" name="absId">
              <a-input v-if="data.form.edit" v-model:value="data.form.absId" />
              <span v-else>{{ data.form.absId }}</span>
            </a-form-item>
            <a-form-item label="部门" name="deptId">
              <DepartmentTreeSelect v-if="data.form.edit" :init="false" v-model:value="data.form.deptId" @update:value="change" />
              <span v-else>{{ data.form.deptName }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6"></a-col>
        </a-row>

        <a-row>
          <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
            <a-tab-pane key="1" tab="生产人员">
              <a-button-group>
                <a-button @click="lineaAdd" type="link" v-if="!data.form.approved && data.form.docStatus === 'O'">
                  <template #icon>
                    <ExportOutlined />
                  </template>

                  插入行
                </a-button>
                <a-button @click="insertAll" type="link" v-if="!data.form.approved && data.form.docStatus === 'O'">
                  <template #icon>
                    <ExportOutlined />
                  </template>

                  全部插入
                </a-button>
              </a-button-group>

              <a-table
                :pagination="{
                  showSizeChanger: true,
                  pageSizeOptions: ['10', '20', '30', '40'],
                  defaultPageSize: 20,
                }"
                :scroll="{ y: 650, x: 3000 }"
                :dataSource="data.form.lista"
                :columns="columnsa"
                rowKey="lineNum"
              >
                <template #bodyCell="{ text, record, column, index }">
                  <template v-if="record.edit && column.dataIndex === 'nowDate'">
                    <a-date-picker v-model:value="record.nowDate" valueFormat="YYYY-MM-DD" />
                  </template>

                  <template v-if="record.edit && column.dataIndex === 'workTimeAll'">
                    <a-checkbox v-model:checked="record.time1">01</a-checkbox>
                    <a-checkbox v-model:checked="record.time2">02</a-checkbox>
                    <a-checkbox v-model:checked="record.time3">03</a-checkbox>
                    <a-checkbox v-model:checked="record.time4">04</a-checkbox>
                    <a-checkbox v-model:checked="record.time5">05</a-checkbox>
                    <a-checkbox v-model:checked="record.time6">06</a-checkbox>
                    <a-checkbox v-model:checked="record.time7">07</a-checkbox>
                    <a-checkbox v-model:checked="record.time8">08</a-checkbox>
                    <a-checkbox v-model:checked="record.time9">09</a-checkbox>
                    <a-checkbox v-model:checked="record.time10">10</a-checkbox>
                    <a-checkbox v-model:checked="record.time11">11</a-checkbox>
                    <a-checkbox v-model:checked="record.time12">12</a-checkbox>
                    <a-checkbox v-model:checked="record.time13">13</a-checkbox>
                    <a-checkbox v-model:checked="record.time14">14</a-checkbox>
                    <a-checkbox v-model:checked="record.time15">15</a-checkbox>
                    <a-checkbox v-model:checked="record.time16">16</a-checkbox>
                    <a-checkbox v-model:checked="record.time17">17</a-checkbox>
                    <a-checkbox v-model:checked="record.time18">18</a-checkbox>
                    <a-checkbox v-model:checked="record.time19">19</a-checkbox>
                    <a-checkbox v-model:checked="record.time20">20</a-checkbox>
                    <a-checkbox v-model:checked="record.time21">21</a-checkbox>
                    <a-checkbox v-model:checked="record.time22">22</a-checkbox>
                    <a-checkbox v-model:checked="record.time23">23</a-checkbox>
                    <a-checkbox v-model:checked="record.time24">24</a-checkbox>
                  </template>

                  <template v-if="!record.edit && column.dataIndex === 'workTimeAll'">
                    <a-tag v-if="record.time1">01</a-tag>
                    <a-tag v-if="record.time2">02</a-tag>
                    <a-tag v-if="record.time3">03</a-tag>
                    <a-tag v-if="record.time4">04</a-tag>
                    <a-tag v-if="record.time5">05</a-tag>
                    <a-tag v-if="record.time6">06</a-tag>
                    <a-tag v-if="record.time7">07</a-tag>
                    <a-tag v-if="record.time8">08</a-tag>
                    <a-tag v-if="record.time9">09</a-tag>
                    <a-tag v-if="record.time10">10</a-tag>
                    <a-tag v-if="record.time11">11</a-tag>
                    <a-tag v-if="record.time12">12</a-tag>
                    <a-tag v-if="record.time13">13</a-tag>
                    <a-tag v-if="record.time14">14</a-tag>
                    <a-tag v-if="record.time15">15</a-tag>
                    <a-tag v-if="record.time16">16</a-tag>
                    <a-tag v-if="record.time17">17</a-tag>
                    <a-tag v-if="record.time18">18</a-tag>
                    <a-tag v-if="record.time19">19</a-tag>
                    <a-tag v-if="record.time20">20</a-tag>
                    <a-tag v-if="record.time21">21</a-tag>
                    <a-tag v-if="record.time22">22</a-tag>
                    <a-tag v-if="record.time23">23</a-tag>
                    <a-tag v-if="record.time24">24</a-tag>
                  </template>

                  <template v-if="column.dataIndex === 'workDay'">
                    {{ text ? '是' : '否' }}
                  </template>
                  <template v-if="column.dataIndex === 'del'">
                    <a-radio-group v-if="record.edit" v-model:value="record.del">
                      <a-radio value="a">正常</a-radio>
                      <a-radio value="b">调休</a-radio>
                      <a-radio value="c">旷工</a-radio>
                    </a-radio-group>
                    <a-tag v-if="!record.edit && text === 'a'">正常</a-tag>
                    <a-tag v-if="!record.edit && text === 'b'">调休</a-tag>
                    <a-tag v-if="!record.edit && text === 'c'">旷工</a-tag>
                  </template>
                  <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                      <a-button
                        :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                        v-if="!record.edit"
                        @click="lineaEdit(record)"
                        type="link"
                      >
                        <template #icon>
                          <FormOutlined />
                        </template>
                      </a-button>
                      <a-button
                        v-if="record.edit"
                        @click="lineaSave(record)"
                        type="link"
                        :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                      >
                        <template #icon>
                          <CheckOutlined />
                        </template>
                      </a-button>
                      <a-button
                        :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                        @click="lineaDel(record)"
                        type="link"
                        danger
                      >
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                      </a-button>
                    </div>
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-row>
      </a-form>
    </a-card>
  </a-spin>
  <userList :visible="data.visible.user" :onClose="onLineaColse"></userList>
  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>
</template>
<script setup>
  import { onMounted, reactive, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { useRouter, useRoute } from 'vue-router';
  import DepartmentTreeSelect from '/@/components/system/department-tree-select/index.vue';
  import userList from '/@/components/business/erp/userList.vue';
  import { nmmordaApi, nmmordApi } from '/@/api/business/erp/nmmord-api';
  import { approvordApi } from '/@/api/business/erp/approvord-api';
  import Approvord from '/@/components/business/erp/approved.vue';
  import { mmordApi } from '/@/api/business/erp/mmord-api.js';

  // ---------------------------- 表格列 ----------------------------
  const route = useRoute();
  const router = useRouter();

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',
      absId: '',
      approved: false,
      docStatus: 'O',
      macName: '测试设备',
      edit: false,
      lista: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
      deptId: [{ required: true, message: '请选择部门' }],
      batchId: [{ required: true, message: '请输入设备名称' }],
      itemName: [{ required: true, message: '请输入设备地址' }],
      nowDate: [{ required: true, message: '' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    activeKey: '1',
    visible: {
      mac: false,
      user: false,
      approvord: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
  });

  const columnsa = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
    },
    {
      title: '员工编码',
      dataIndex: 'userId',
      align: 'center',
    },
    {
      title: '员工名称',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '日期',
      dataIndex: 'nowDate',
      align: 'center',
      width: 140,
    },
    {
      title: '正常',
      dataIndex: 'workTime',
      align: 'right',
    },
    {
      title: '平常',
      dataIndex: 'common',
      align: 'right',
    },

    {
      title: '公休',
      dataIndex: 'overTime',
      align: 'right',
    },
    {
      title: '节假',
      dataIndex: 'holiday',
      align: 'right',
    },

    {
      title: '工作时间',
      dataIndex: 'workTimeAll',
      align: 'center',
      width: 1200,
    },
    {
      title: '星期',
      dataIndex: 'week',
      align: 'center',
    },
    {
      title: '工作日',
      dataIndex: 'workDay',
      align: 'center',
    },
    {
      title: '类型',
      dataIndex: 'del',
      align: 'center',
      width: 300,
    },

    {
      title: '月期间',
      dataIndex: 'absId',
      align: 'center',
    },
    {
      title: '行状态',
      dataIndex: 'lineStatus',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      fixed: 'right',
      align: 'center',
    },
  ]);
  const tableLoading = ref(false);
  const formRef = ref(null);

  // 初始化
  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  onMounted(init);

  // 查询数据
  function queryData() {
    tableLoading.value = true;
    formRef.value.resetFields();
    nmmordApi
      .info(data.form.docEntry)
      .then((res) => {
        data.form = res.data;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }

  function back() {
    router.push({ path: '/erp/nmmord' });
  }

  function add() {
    data.form.objId = 78;

    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/erp/nmmorda', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          nmmordApi.update(data.form).then((res) => {
            queryData(data.form.docEntry);
            message.success('修改成功！');
          });
        } else {
          nmmordApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/erp/nmmorda', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        nmmordApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/erp/nmmord' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      nmmordApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      nmmordApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'c') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'B',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    }
  }

  function refresh() {
    queryData();
  }

  function change(item, key) {
    data.form.deptName = key;
  }

  // 审核------------------------------------------------------------------------------------------------
  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  /* -------------------------------------A---------------------------------------------- */

  function insertAll() {
    tableLoading.value = true;
    nmmordApi.batchInsert(data.form.docEntry).then((res) => {
      tableLoading.value = false;
    });
  }

  function onLineaColse(item) {
    data.visible.user = false;
    item.forEach((item) => {
      data.form.lista.push({
        docEntry: data.form.docEntry,
        lineNum: null,
        userId: item.employeeId,
        userName: item.actualName,
        absId: data.form.absId,
        nowDate: null,
        workDay: false,
        week: '',
        festName: '',
        multiple: 1,
        edit: true,
        lineStatus: 'O',
        approved: false,
        time1: false,
        time2: false,
        time3: false,
        time4: false,
        time5: false,
        time6: false,
        time7: false,
        time8: false,
        time13: false,
        time14: false,
        time19: false,
        time20: false,
        time21: false,
        time22: false,
        time23: false,
        time24: false,
        time9: true,
        time10: true,
        time11: true,
        time12: true,
        time15: true,
        time16: true,
        time17: true,
        time18: true,
        del: 'a',
      });
    });
  }

  function lineaEdit(key) {
    key.edit = true;
  }

  function lineaAdd() {
    data.visible.user = true;
  }

  function lineaSave(item) {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (item.lineNum) {
          nmmordaApi
            .update(item)
            .then((res) => {
              item.edit = false;
              tableLoading.value = false;
              queryData();
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        } else {
          nmmordaApi
            .add(item)
            .then((res) => {
              item.edit = false;
              tableLoading.value = false;
              queryData();
            })
            .catch((err) => {
              tableLoading.value = false;
            });
        }
      })
      .catch((err) => {
        message.error('页面校验失败！');
      });
  }

  function lineaDel(item) {
    tableLoading.value = true;
    nmmordaApi.deleteLine(item).then((res) => {
      queryData();
    }).finally(() => {
      tableLoading.value = false;
    })
  }
</script>
